#  Copyright (C) 2006 Sham Chukoury <eleusis@xmms.org>
#
#  This library is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public
#  License as published by the Free Software Foundation; either
#  version 2.1 of the License, or (at your option) any later version.
#
#  This library is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  Lesser General Public License for more details.

import Chalyx
import mpdconnector
import gobject

class MPDGLibConnector(mpdconnector.MPDConnector):
	def __init__(self, mpd, pingInterval = 5, args = None):
		mpdconnector.MPDConnector.__init__(self, mpd, pingInterval, args)
		self.timerID = gobject.timeout_add(self.statusTimeout, self.status_check)
		mpd.do.set_need_out_fun(self.need_out)
		gobject.io_add_watch(mpd.do.get_fd(), gobject.IO_IN | gobject.IO_HUP, self.handle_in)
		self.has_out_watch = False

	def need_out(self, i):
		if self.mpd.do.want_ioout() and not self.has_out_watch:
			gobject.io_add_watch(self.mpd.do.get_fd(), gobject.IO_OUT, self.handle_out)
			self.has_out_watch = True

	def handle_in(self, source, cond):
		if cond & gobject.IO_HUP:
			self.mpd.s_disconnect()
			return False
		if cond & gobject.IO_IN:
			self.mpd.do.ioin()
		return True
	
	def handle_out(self, source, cond):
		if cond == gobject.IO_OUT and self.mpd.do.want_ioout():
			self.mpd.do.ioout()
		self.has_out_watch = self.mpd.do.want_ioout()
		return self.has_out_watch

	def stop(self):
		gobject.source_remove(self.timerID)
		return mpdconnector.MPDConnector.stop(self)
